﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NeuralStock.DomainService.Interfaces;
using NeuralStock.Tools;
using NeuralStock.Entities;

namespace NeuralStock.DomainService.Implementation
{
    public class GpwCompanyQuotationImportService : BaseService, IGpwCompanyQuotationImportService
    {
        ICompanyService companyService;
        ICompanyQuotationService companyQuotationService;

        public GpwCompanyQuotationImportService(ICompanyService companyService, ICompanyQuotationService companyQuotationService)
        {
            this.companyService = companyService;
            this.companyQuotationService = companyQuotationService;
        }

        public void ImportData()
        {
            throw new NotSupportedException();
        }

        public void ImportDataFromLocal()
        {
            var data = ReadDataFromLocal();

            ImportGpwQuotesList(data);
        }

        public void ImportDataFromWeb(DateTime dateFrom, DateTime dateTo)
        {
            var data = ReadDataFromWeb(dateFrom, dateTo);

            ImportGpwQuotesList(data);
        }

        private void ImportGpwQuotesList(List<GpwQuoteData> data)
        {
            foreach (var item in data)
            {
                var company = companyService.Get(item.CompanyName);

                if (company != null)
                {
                    if (companyQuotationService.QuotationExists(company.Id, item.Date))
                    {
                        companyQuotationService.UpdateQuotation(company.Id, item.Date, item.Price.Value);
                    }
                    else
                    {
                        companyQuotationService.CreateQuotation(company.Id, item.Date, item.Price.Value);
                    }
                    Console.WriteLine("Imported: {0}, {1} {2}", item.CompanyName, item.Date, item.Price);
                }
            }
        }

        private List<GpwQuoteData> ReadDataFromLocal()
        {
            GpwQuotesProvider downloader = new GpwQuotesProvider();
            return downloader.GetQuotesFromLocal();
        }

        private List<GpwQuoteData> ReadDataFromWeb(DateTime dateFrom, DateTime dateTo)
        {
            GpwQuotesProvider downloader = new GpwQuotesProvider();
            return downloader.GetQuotesFromWeb(dateFrom, dateTo);
        }
    }
}
